<?php
namespace app\chat\controller;
use app\chat\model\ChatMsg;
use app\chat\model\ChatUser;
use app\common\model\User as UserModel;
use app\common\model\Loginstatus;
use app\common\model\Config;
use app\common\model\MallConfig;

use app\service\LogService;
use app\service\WechatService;

use think\Db;
use think\Exception;
class Index
{
    public $userInfo;
    public $input;
    public $groupId;
    public function __construct () {
        config(Config::getConfig());
        $this->chatMsgModel = new ChatMsg;
        $this->chatUserModel = new ChatUser;
        $this->userModel = new UserModel;
        $input = file_get_contents('php://input');
        if($input) {
            $arr = json_decode($input,true);
            $this->input = $arr;
        }
        $token = input('token');
        if(!$token && $arr) {
            $token = $arr['token'];
        }
        if($token) {
           /*  $this->userInfo = $this->userModel->getOne([
                'token' => $token
            ]); */
            $loginstatus = Loginstatus::getOne([
                'session_token' => $token
            ]);
            if($loginstatus&&$loginstatus['expire_time']>time()) {
                $this->userInfo = $this->userModel->getOne([
                    'id' =>$loginstatus['uid']
                ]);
                config(MallConfig::getConfig($this->userInfo['mall_id']));
                $this->groupId = UserModel::getGroupId($this->userInfo['id']);
            }
        }
    }
    public function index()
    {
       _pr(input());
    }

    /* 加入团队 */
    public function join() {
        $input = $this->input;
        if(!$input['content']) {
            $view = MallConfig::getOne([
                'mall_id' => $this->userInfo['mall_id'],
                'name' => 'chat_view'
            ]);
            if(!$view) {
                MallConfig::create([
                    'mall_id' => $this->userInfo['mall_id'],
                    'name' => 'chat_view',
                    'value' => 1000
                ]);
            }
            MallConfig::where([
                'mall_id' => $this->userInfo['mall_id'],
                'name' => 'chat_view'
            ])->setInc('value');
        }
        ChatUser::create([
            'uid' => $this->userInfo['id'],
            'client_id' => $input['client_id'],
            'status' => 1
        ]);
    }

    public function quit() {
        $user = ChatUser::where('client_id',$this->input['client_id'])->delete();
    }

    public function message() {
        try {
            if(!$this->userInfo) {
                return returnJson(1,'');
            }
            $arr = $this->input;
            $arr['uid'] = $this->userInfo['id'];

            //这部分类型的消息不存储
            if(in_array($arr['content']['type'],[
                'banned','unbanned'
            ])) {
                return returnJson(0,'');
            }
            MallConfig::where([
                'mall_id' => $this->userInfo['mall_id'],
                'name' => 'chat_view'
            ])->setInc('value');

            //这部分类型消息禁言用户不能发送(之外的比如购物,发红包不禁言)
            if(in_array($arr['content']['type'],[
                'text','at','atAll','image','voice','expression','video'
            ])) {
               /*  if(!in_array($this->userInfo['id'],explode(',',config('chat_manager')))) {
                    if(config('chat_forbidden')) {
                        return returnJson(1,'全员禁言中');
                    }
                } */

                if(!UserModel::isManager($this->userInfo['id'])) {
                    if(config('chat_forbidden')) {
                        return returnJson(1,'全员禁言中');
                    }
                }
                
                if($this->userInfo['chat_forbidden']) {
                    return returnJson(1,'禁言中');
                }
                if(in_array($arr['content']['type'],[
                    'text','at','atAll'
                ])) {
                    if(ChatMsg::isBan($arr['content']['content'])) {
                        return returnJson(1,'包含禁词');
                    }
                }
    
            }
            
            
            $url = request()->domain()."/m/chat/pages/index/index?mall_id={$this->userInfo['mall_id']}";
            if($arr['content']['type']=='at') {
                //@其他人 发客服消息
                WechatService::S([
                    'mall_id' => $this->userInfo['mall_id']
                ])->send(
                    1,
                    UserModel::uid2openid($arr['content']['uid']),
                    $this->userInfo['nickname']."在群里@了你,<a href='{$url}'>点击查看说了些什么</a>"
                );
            }elseif($arr['content']['type']=='atAll') {

                $host=get_host();
                //@所有人
                $array['mall_id']=$this->userInfo['mall_id'];
                $array['type']="chat";//$_GET['type'];
                $array['nick_name']=$this->userInfo['nickname'];//$_GET['nick_name'];
                $array['url']=$url;
                //LogService::S()->writeLog('log','array',$host);
                $re=doRequest($host,'/api/test/kefu_script',$array);//异步通知
                LogService::S()->writeLog('re','data',$re);
                /*//@所有人
                $obj = WechatService::S([
                    'mall_id' => $this->userInfo['mall_id']
                ]);

                $where['zkhb_loginstatus.update_time']=array("EGT",time()-3600*24);
                //Loginstatus::getAll(,'','uid');
                $recentList = Db::name("user_wechat")
                    ->field("zkhb_user_wechat.uid,zkhb_user_wechat.openid")
                    ->join("zkhb_loginstatus","zkhb_user_wechat.uid=zkhb_loginstatus.uid")
                    ->where($where)
                    ->select();

                // LogService::S()->writeLog('st','user',$recentList);
                //$recentList = UserModel::getRencentList($this->userInfo['id']);
                if($recentList) {
                    foreach($recentList as $v) {
                        $obj->send(
                            1,
                            $v['openid'],
                            //UserModel::uid2openid($v['uid']),
                            "急事，群主{$this->userInfo['nickname']}在群里对你说:<a href='{$url}'>点击查看说了些什么</a>"
                        );
                    }
                }*/
            }
            $msg = [
                'content' => json_encode($arr),
                'uid' => $this->userInfo['id'],
                'create_time' => time(),
                'mall_id' => $this->userInfo['mall_id'],
                'group_id' => $this->groupId,
                'type' => $arr['content']['type']
            ];
            $id = $this->chatMsgModel->insertGetId($msg);
            return returnJson(0,'',$id);
        } catch (Exception $ex){
            LogService::S()->writeLog('Exception',$ex->getMessage());
            $this->ajax(202,$ex->getMessage());
        }
    }

    /* 撤回 */
    public function revoke() {
        if(!$this->userInfo) {
            return returnJson(1,'');
        }
        $arr = $this->input;
        $message = $this->chatMsgModel->getOne([
            'id' => $arr['id'],
            //'uid' => $arr['uid']
        ]);
        if(!$message) {
            return returnJson(1,'');
        }
        //管理员允许撤回任意用户消息
       /*  if(!in_array($this->userInfo['id'],explode(',',config('chat_manager')))) {
            if($message['uid']!=$this->userInfo['id']) {
                return returnJson(1,'');
            }
        } */

        if(!UserModel::isManager($this->userInfo['id'])) {
            if($message['uid']!=$this->userInfo['id']) {
                return returnJson(1,'');
            }
        }
        
        $this->chatMsgModel->where('id',$message['id'])->update([
            'revoke' => 1
        ]);
        return returnJson(0,'success');
    }

    /* 消息队列的消息列表 */
    public function messageList() {
        if(!$this->userInfo) {
            return returnJson(1,'');
        }
        $where = [
            'status' => 0,
            'group_id' => $this->groupId
        ];
        $list =  $this->chatMsgModel->getAll($where);
        $this->chatMsgModel->where($where)->update([
            'status' => 1
        ]);
        if(!$list) {
            return returnJson(1,'');
        }
        return returnJson(0,'',$list);
    }
  
    /* 获取用户信息 */
  	 public function token2uid () {
        try {
            if(!$this->userInfo) {
                return returnJson(1,'');
            }
            return returnJson(0,'',[
                'uid' => $this->userInfo['id'],
                //'mall_id' => $this->userInfo['mall_id']
                'mall_id' => $this->groupId
            ]);
        } catch (Exception $ex){
            LogService::S()->writeLog('Exception',$ex->getMessage());
            $this->ajax(202,$ex->getMessage());
        }
    }


}
